package cn.sc.summer.admin.config;

import cn.sc.summer.constant.project.ProjectConstant;
import cn.sc.summer.token.handler.server.AccessDeniedHandlerX;
import cn.sc.summer.token.handler.server.AuthenticationEntryPointX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.annotation.Resource;

@Slf4j
@Order(-1)
@Configuration
@EnableWebSecurity
public class SecurityServerConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private AuthorizationServerManagerX authorizationServerManagerX;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        log.info("==> Start initialization the {} Spring Security config...", ProjectConstant.SERVER_NAME);

        //端点检测放行
        httpSecurity.authorizeHttpRequests()
                .requestMatchers(EndpointRequest.toAnyEndpoint())
                .permitAll()
                .anyRequest()
                .access(authorizationServerManagerX);

        //关闭表单登录
        httpSecurity.formLogin()
                .disable()
                .logout()
                .disable();

        //关闭csrf防护
        httpSecurity.csrf()
                .disable();

        // 禁用httpBasic
        httpSecurity.httpBasic()
                .disable();

        //异常处理
        httpSecurity.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPointX())
                .accessDeniedHandler(new AccessDeniedHandlerX());

    }

}

